package com.usian.comment.service.impl;

import com.sun.org.apache.regexp.internal.RE;
import com.usian.comment.feign.UserFeign;
import com.usian.comment.service.CommentService;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.comment.vo.ApCommentVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.ThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeign userFeign;

    //评论
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        if (dto == null || dto.getArticleId() == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (StringUtils.isBlank(dto.getContent()))
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能为空");
        if (dto.getContent().length() > 140)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能超过140字");
        Integer userId = ThreadLocalUtils.getUser();
        if (userId == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        ApUser apUser = userFeign.findUserById(userId);
        ApComment comment = new ApComment();
        comment.setUserId(userId);
        comment.setUserName(apUser.getName());
        comment.setEntryId(dto.getArticleId());
        comment.setChannelId(dto.getChannelId() == null ? 1 : dto.getChannelId());//频道Id
        comment.setType((short) 0);
        comment.setContent(dto.getContent());
        comment.setImage(apUser.getImage());
        comment.setLikes(0);
        comment.setReply(0);
        comment.setFlag((short) 0);
        comment.setLatitude(new BigDecimal("116.0000"));
        comment.setLongitude(new BigDecimal("41.0000"));
        comment.setCreatedTime(new Date());
        comment.setUpdatedTime(new Date());
        mongoTemplate.save(comment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult like(CommentLikeDto dto) {
        if (dto == null || dto.getCommentId() == null || dto.getOperation() == null)
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
        if (dto.getOperation() != 0 && dto.getOperation() != 1)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        Integer userId = ThreadLocalUtils.getUser();
        if (userId == null) return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        ApComment apComment = mongoTemplate.findById(userId, ApComment.class);
        if (apComment == null) return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        if (dto.getOperation() == 0) {
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setUserId(apComment.getUserId());
            apCommentLike.setCommentId(dto.getCommentId());
            apCommentLike.setOperation((short) 0);
            mongoTemplate.save(apCommentLike);
            apComment.setLikes(apComment.getLikes() + 1);
        } else {
            ApCommentLike templateOne = mongoTemplate.findOne(Query.query(Criteria.where("userId").is(apComment.getUserId()).and("commentId").is(apComment.getId())), ApCommentLike.class);
            if (templateOne == null) return ResponseResult.okResult(AppHttpCodeEnum.PARAM_INVALID);
            apComment.setLikes(apComment.getLikes() - 1);
            mongoTemplate.remove(ApCommentLike.class);
        }
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        if (dto == null || dto.getArticleId() == null) return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        if (dto.getMinDate() == null) dto.setMinDate(new Date());
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate())).with(Sort.by(Sort.Direction.DESC, "createdTime")).limit(10);
        Integer userId = ThreadLocalUtils.getUser();
        List<ApComment> commentList = mongoTemplate.find(query, ApComment.class);
        if (userId != null) {
            List<String> commentIdList = commentList.stream().map(c -> c.getId()).collect(Collectors.toList());
            Query queryCommentLikes = Query.query(Criteria.where("userId").is(userId).and("commentId").in(commentIdList));
            //分页10条数据点的赞
            List<ApCommentLike> myCommentLikes = mongoTemplate.find(queryCommentLikes, ApCommentLike.class);
            List<ApCommentVo> voList = new ArrayList<>();
            for (ApComment comment : commentList) {//每一个评论信息
                ApCommentVo vo = new ApCommentVo();
                BeanUtils.copyProperties(comment,vo);
                vo.setOperation(1);
                for (ApCommentLike myCommentLike : myCommentLikes) {
                    if (myCommentLike.getCommentId().equals(comment.getId())){
                        vo.setOperation(0);
                        break;
                    }
                }
                voList.add(vo);
            }
            return ResponseResult.okResult(voList);
        }
        return ResponseResult.okResult(commentList);
    }
}
